package com.chengda.dashboard.controller;

import com.chengda.dashboard.common.Result;
import com.chengda.dashboard.entity.*;
import com.chengda.dashboard.mapper.FactoryScreenInfoMapper;
import com.chengda.dashboard.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 大屏数据控制器
 */
@RestController
@RequestMapping("/dashboard")
@CrossOrigin(origins = "*")
public class DashboardController {

    @Autowired
    private MachineInfoService machineInfoService;

    @Autowired
    private FactoryScreenInfoService factoryScreenInfoService;

    @Autowired
    private FactoryScreenInfoMapper factoryScreenInfoMapper;

    @Autowired
    private WorkshopInfoService workshopInfoService;

    @Autowired
    private AnnouncementInfoService announcementInfoService;

    @Autowired
    private AlarmInfoService alarmInfoService;

    @Autowired
    private SysTemporaryService sysTemporaryService;

    @Autowired
    private FactoryMachineInfoService factoryMachineInfoService;

    /**
     * 获取机台信息
     * @param workshopType 车间类型
     * @return 机台信息列表
     */
    @GetMapping("/machine-info")
    public Result<List<MachineInfo>> getMachineInfo(@RequestParam(defaultValue = "经编1") String workshopType) {
        try {
            // 从factory_screen_info表获取数据
            List<FactoryScreenInfo> factoryScreenInfoList = factoryScreenInfoService.getMachineInfoByWorkshop();
            List<MachineInfo> machineInfoList = convertToMachineInfo(factoryScreenInfoList);
            return Result.success(machineInfoList);
        } catch (Exception e) {
            return Result.error("获取机台信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取自定义机台信息
     * @param workshopType 车间类型
     * @return 自定义机台信息列表
     */
    @GetMapping("/custom-machine-info")
    public Result<List<MachineInfo>> getCustomMachineInfo(@RequestParam(defaultValue = "经编1") String workshopType) {
        try {
            // 从factory_screen_info表获取数据
            List<FactoryScreenInfo> factoryScreenInfoList = factoryScreenInfoService.getCustomMachineInfoByWorkshop();
            List<MachineInfo> customMachineInfoList = convertToCustomMachineInfo(factoryScreenInfoList);
            return Result.success(customMachineInfoList);
        } catch (Exception e) {
            return Result.error("获取自定义机台信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取车间信息
     * @return 车间信息列表
     */
    @GetMapping("/workshop-info")
    public Result<List<WorkshopInfo>> getWorkshopInfo() {
        try {
            // 从数据库获取车间信息
            List<WorkshopInfo> workshopInfoList = workshopInfoService.getAllWorkshopInfo();
            return Result.success(workshopInfoList);
        } catch (Exception e) {
            return Result.error("获取车间信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取公告信息
     * @return 公告信息列表
     */
    @GetMapping("/announcement-info")
    public Result<List<AnnouncementInfo>> getAnnouncementInfo() {
        try {
            // 从数据库获取公告信息
            List<AnnouncementInfo> announcementInfoList = announcementInfoService.getAllAnnouncementInfo();
            return Result.success(announcementInfoList);
        } catch (Exception e) {
            return Result.error("获取公告信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取报警信息
     * @return 报警信息列表
     */
    @GetMapping("/alarm-info")
    public Result<List<AlarmInfo>> getAlarmInfo() {
        try {
            // 从数据库获取报警信息
            List<AlarmInfo> alarmInfoList = alarmInfoService.getAllAlarmInfo();
            return Result.success(alarmInfoList);
        } catch (Exception e) {
            return Result.error("获取报警信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取大屏所有数据
     * @param workshopType 车间类型
     * @return 大屏数据
     */
    @GetMapping("/all-data")
    public Result<Map<String, Object>> getAllData(@RequestParam(defaultValue = "经编1") String workshopType) {
        try {
            Map<String, Object> data = new HashMap<>();
            
            // 从数据库获取所有数据
            List<FactoryScreenInfo> factoryScreenInfoList = factoryScreenInfoService.getMachineInfoByWorkshop();
            List<MachineInfo> machineInfoList = convertToMachineInfo(factoryScreenInfoList);
            data.put("machineInfo", machineInfoList);
            
            List<FactoryScreenInfo> customFactoryScreenInfoList = factoryScreenInfoService.getCustomMachineInfoByWorkshop();
            List<MachineInfo> customMachineInfoList = convertToCustomMachineInfo(customFactoryScreenInfoList);
            data.put("customMachineInfo", customMachineInfoList);

            data.put("workshopInfo", new ArrayList<>());
            data.put("announcementInfo", new ArrayList<>());
            data.put("alarmInfo", new ArrayList<>());
            
            return Result.success(data);
        } catch (Exception e) {
            return Result.error("获取大屏数据失败: " + e.getMessage());
        }
    }

    /**
     * 添加或更新机台信息
     * @param machineInfo 机台信息
     * @return 操作结果
     */
    @PostMapping("/machine-info")
    public Result<Boolean> saveOrUpdateMachineInfo(@RequestBody MachineInfo machineInfo) {
        try {
            boolean result = machineInfoService.saveOrUpdateMachineInfo(machineInfo);
            return result ? Result.success(true) : Result.error("保存机台信息失败");
        } catch (Exception e) {
            return Result.error("保存机台信息失败: " + e.getMessage());
        }
    }

    /**
     * 删除机台信息
     * @param id 机台信息ID
     * @return 操作结果
     */
    @DeleteMapping("/machine-info/{id}")
    public Result<Boolean> deleteMachineInfo(@PathVariable Long id) {
        try {
            boolean result = machineInfoService.deleteMachineInfo(id);
            return result ? Result.success(true) : Result.error("删除机台信息失败");
        } catch (Exception e) {
            return Result.error("删除机台信息失败: " + e.getMessage());
        }
    }

    // ==================== 数据转换方法 ====================

    /**
     * 将FactoryScreenInfo转换为MachineInfo
     */
    private List<MachineInfo> convertToMachineInfo(List<FactoryScreenInfo> factoryScreenInfoList) {
        List<MachineInfo> machineInfoList = new ArrayList<>();
        
        for (FactoryScreenInfo factoryScreenInfo : factoryScreenInfoList) {
            MachineInfo machineInfo = new MachineInfo();
            machineInfo.setId(factoryScreenInfo.getId());
            machineInfo.setMachineNo(factoryScreenInfo.getMachineId());
            machineInfo.setWarpBeamNo("GB"+factoryScreenInfo.getGbNum());
            machineInfo.setRemainingTime(factoryScreenInfo.getLeftTime());
            machineInfo.setNextWarpingHeads(factoryScreenInfo.getBeamSetNum());
//            machineInfo.setWorkshopType(factoryScreenInfo.getWorkshopType());
//            machineInfo.setIsCustom(factoryScreenInfo.getIsCustom());
            
            // 获取原料名称
            String materialName = factoryScreenInfoService.getMaterialName(factoryScreenInfo.getMachineId(), factoryScreenInfo.getGbNum());
            machineInfo.setMaterialName(materialName != null ? materialName : "");
            
            // 计算换轴时间：当前时间 + 剩余时间
            String shaftChangeTime = calculateShaftChangeTime(factoryScreenInfo.getLeftTime());
            machineInfo.setShaftChangeTime(shaftChangeTime);
            
            machineInfoList.add(machineInfo);
        }
        
        return machineInfoList;
    }

    /**
     * 将FactoryScreenInfo转换为自定义机台MachineInfo（经轴号添加GB前缀）
     */
    private List<MachineInfo> convertToCustomMachineInfo(List<FactoryScreenInfo> factoryScreenInfoList) {
        List<MachineInfo> machineInfoList = new ArrayList<>();
        
        for (FactoryScreenInfo factoryScreenInfo : factoryScreenInfoList) {
            MachineInfo machineInfo = new MachineInfo();
            machineInfo.setId(factoryScreenInfo.getId());
            machineInfo.setMachineNo(factoryScreenInfo.getMachineId());
            // 为自定义机台信息的经轴号添加GB前缀
            String gbNum = factoryScreenInfo.getGbNum();
            if (gbNum != null && !gbNum.isEmpty()) {
                machineInfo.setWarpBeamNo("GB" + gbNum);
            } else {
                machineInfo.setWarpBeamNo(gbNum);
            }
            machineInfo.setRemainingTime(factoryScreenInfo.getLeftTime());
            machineInfo.setNextWarpingHeads(factoryScreenInfo.getBeamSetNum());
//            machineInfo.setWorkshopType(factoryScreenInfo.getWorkshopType());
//            machineInfo.setIsCustom(factoryScreenInfo.getIsCustom());
            
            // 获取原料名称
            String materialName = factoryScreenInfoService.getMaterialName(factoryScreenInfo.getMachineId(), factoryScreenInfo.getGbNum());
            machineInfo.setMaterialName(materialName != null ? materialName : "");
            
            // 计算换轴时间：当前时间 + 剩余时间
            String shaftChangeTime = calculateShaftChangeTime(factoryScreenInfo.getLeftTime());
            machineInfo.setShaftChangeTime(shaftChangeTime);
            
            machineInfoList.add(machineInfo);
        }
        
        return machineInfoList;
    }

    /**
     * 计算换轴时间：当前时间 + 剩余时间，转换为HH:mm格式
     * @param remainingTime 剩余时间（小时）
     * @return 换轴时间字符串（HH:mm格式）
     */
    private String calculateShaftChangeTime(java.math.BigDecimal remainingTime) {
        if (remainingTime == null) {
            return "";
        }
        
        try {
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            
            // 将剩余时间转换为分钟
            double remainingMinutes = remainingTime.doubleValue() * 60;
            
            // 计算换轴时间
            LocalDateTime shaftChangeTime = now.plusMinutes((long) remainingMinutes);
            
            // 格式化为HH:mm
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
            return shaftChangeTime.format(formatter);
        } catch (Exception e) {
            // 如果计算失败，返回空字符串
            return "";
        }
    }

    /**
     * 获取界面风格列表
     * @return 可用的界面风格
     */
    @GetMapping("/ui-styles")
    public Result<List<Map<String, String>>> getUIStyles() {
        try {
            List<Map<String, String>> styles = new ArrayList<>();
            
            Map<String, String> classicStyle = new HashMap<>();
            classicStyle.put("id", "classic");
            classicStyle.put("name", "经典风格");
            classicStyle.put("description", "传统的蓝色主题界面");
            classicStyle.put("url", "/index.html");
            classicStyle.put("preview", "/static/images/classic-preview.png");
            styles.add(classicStyle);
            
            Map<String, String> modernStyle = new HashMap<>();
            modernStyle.put("id", "modern");
            modernStyle.put("name", "现代风格");
            modernStyle.put("description", "现代化的渐变主题界面");
            modernStyle.put("url", "/modern.html");
            modernStyle.put("preview", "/static/images/modern-preview.png");
            styles.add(modernStyle);
            
            return Result.success(styles);
        } catch (Exception e) {
            return Result.error("获取界面风格失败: " + e.getMessage());
        }
    }

    /**
     * 获取系统状态信息
     * @return 系统状态
     */
    @GetMapping("/system-status")
    public Result<Map<String, Object>> getSystemStatus() {
        try {
            Map<String, Object> status = new HashMap<>();
            
            // 从factory_machine_info表获取机台总数（type=10）
            Integer totalMachines = factoryMachineInfoService.countByType(10);
            if (totalMachines == null) {
                totalMachines = 0;
            }
            
            // 从sys_temporary表获取运行率（type='1', name='efficiency'）
            String efficiencyValue = sysTemporaryService.getValueByTypeAndNameStr("1", "efficiency");
            int runningRate = 0; // 默认值
            if (efficiencyValue != null && !efficiencyValue.isEmpty()) {
                try {
                    // 将小数字符串乘以100转换为百分比
                    double efficiency = Double.parseDouble(efficiencyValue);
                    runningRate = (int) Math.round(efficiency * 100);
                } catch (NumberFormatException e) {
                    // 如果转换失败，使用默认值
                    runningRate = 0;
                }
            }

            // 从sys_temporary表获取今日总产量（type='1', name='currentAmount'）
            String currentAmountValue = sysTemporaryService.getValueByTypeAndNameStr("1", "currentAmount");
            int currentAmount = 0; // 今日总产量
            if (currentAmountValue != null && !currentAmountValue.isEmpty()) {
                try {
                    currentAmount = (int) Math.round(Double.parseDouble(currentAmountValue));
                } catch (NumberFormatException e) {
                    currentAmount = 0;
                }
            }
            
            // 从sys_temporary表获取昨日总产量（type='1', name='yesterdayAmount'）
            String yesterdayAmountValue = sysTemporaryService.getValueByTypeAndNameStr("1", "yesterdayAmount");
            int yesterdayAmount = 0; // 昨日总产量
            if (yesterdayAmountValue != null && !yesterdayAmountValue.isEmpty()) {
                try {
                    yesterdayAmount = (int) Math.round(Double.parseDouble(yesterdayAmountValue));
                } catch (NumberFormatException e) {
                    yesterdayAmount = 0;
                }
            }
            
            status.put("totalMachines", totalMachines);
            status.put("currentAmount", currentAmount); // 今日总产量
            status.put("yesterdayAmount", yesterdayAmount); // 昨日总产量
            status.put("runningRate", runningRate);
            status.put("systemTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            status.put("status", "online");
            
            return Result.success(status);
        } catch (Exception e) {
            return Result.error("获取系统状态失败: " + e.getMessage());
        }
    }
}